package calculator

import (
	"context"
	"net"

	"gitee.com/allowall-package/goutil/fn"
	grpc "google.golang.org/grpc"
)

var ServerAddr = ":8080"

// 服务
type calculator struct{}

// 方法
func (c calculator) Add(ctx context.Context, in *CalculatorRequest) (*CalculatorResponse, error) {
	resp := new(CalculatorResponse)
	resp.Res = in.Num1 + in.Num2
	return resp, nil
}

var Calculator = calculator{}

func GrpcServerRun() error {
	listen, err := net.Listen("tcp", ServerAddr)
	if err != nil {
		return err
	}

	// 实例化grpc Server
	s := grpc.NewServer()

	// 注册CalculatorServer
	RegisterCalculatorServer(s, Calculator)

	fn.Dump(fn.FuncInfo()+"GrpcServerRun with", ServerAddr)
	return s.Serve(listen)
}

func GrpcClientCall() {
	// 连接
	conn, err := grpc.Dial(ServerAddr, grpc.WithInsecure())
	if err != nil {
		fn.Dump(fn.FuncInfo(), err)
		return
	}
	defer conn.Close()

	// 初始化客户端
	c := NewCalculatorClient(conn)

	// 调用方法
	req := &CalculatorRequest{Num1: 1, Num2: 2}
	res, _ := c.Add(context.Background(), req)

	fn.Dump(fn.FuncInfo(), res)
}
